package com.project.springboot.controller;

import com.gitee.yongzhuzl.commonutil.util.date.CalendarUtil;
import com.gitee.yongzhuzl.commonutil.util.file.FileUtil;
import com.gitee.yongzhuzl.commonutil.util.qr.QRCodeUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * description: 下载文件相关API
 * @author 朱正磊
 * @date 2023-12-27 09:26:57
 */
@RestController
@RequestMapping("/download")
public class DownloadController {

    /**
     * <a href="http://127.0.0.1:8080/download/downloadTxt">...</a>
     * description: 下载文本到客户端
     * @author 朱正磊
     * @date 2023-12-27 09:29:29
     * @param response HTTP响应对象
     */
    @GetMapping("/downloadTxt")
    public void downloadTxt(HttpServletResponse response) {
        try {
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");
            String nowDate = CalendarUtil.getNowDate("yyyyMMddHHmmssSSS");
            String fileName = URLEncoder.encode("自我介绍", StandardCharsets.UTF_8) + "-" + nowDate + ".txt";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            String content = "大家好，我是李小龙";
            byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
            servletOutputStream.write(bytes, 0, bytes.length);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <a href="http://127.0.0.1:8080/download/downloadImage">...</a>
     * description: 下载图片到客户端
     * @author 朱正磊
     * @date 2023-12-27 10:16:05
     * @param response HTTP响应对象
     */
    @GetMapping("/downloadImage")
    public void downloadImage(HttpServletResponse response) {
        try {
            response.setContentType("image/png");
            response.setCharacterEncoding("UTF-8");
            String nowDate = CalendarUtil.getNowDate("yyyyMMddHHmmssSSS");
            String fileName = URLEncoder.encode("图片文件", StandardCharsets.UTF_8) + "-" + nowDate + ".png";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            BufferedImage bufferedImage = QRCodeUtil
                    .getQRCodeImage("1727138588721725447", "连包中药库:11-11-31");
            ImageIO.write(bufferedImage, "png", servletOutputStream);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <a href="http://127.0.0.1:8080/download/downloadZip">...</a>
     * description: 下载压缩文件到客户端
     * @author 朱正磊
     * @date 2023-12-27 10:34:17
     * @param response HTTP响应对象
     */
    @GetMapping("/downloadZip")
    public void downloadZip(HttpServletResponse response) {
        try {
            response.setContentType("application/zip");
            response.setCharacterEncoding("UTF-8");
            String nowDate = CalendarUtil.getNowDate("yyyyMMddHHmmssSSS");
            String fileName = URLEncoder.encode("药架码", StandardCharsets.UTF_8) + "-" + nowDate + ".zip";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(servletOutputStream);
            this.zip(zipOutputStream);
            zipOutputStream.flush();
            zipOutputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * description: zip压缩
     * @author 朱正磊
     * @date 2023-12-27 11:12:46
     * @param zipOutputStream zip输出流
     * @throws Exception 异常信息
     */
    private void zip(ZipOutputStream zipOutputStream) throws Exception {
        List<String> contentList = new ArrayList<>();
        Stream.iterate(0, i -> i + 1).limit(1000).forEach(i -> {
            String content = Integer.toString(i + 1);
            contentList.add(content);
        });
        // String filePath = "D:\\qr\\" + CalendarUtil.getNowDate("yyyy-MM-dd");
        // 如果临时文件夹不存在就创建
        // FileUtil.createFile(filePath);
        for (String content : contentList) {
            BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content, "药架码-" + content);
            String fileName = content + ".png";
            // String fileUri = filePath + "\\" + fileName;
            String fileUri = "D:\\" + fileName;
            // 在本地创建临时文件
            FileOutputStream fileOutputStream = new FileOutputStream(fileUri);
            ImageIO.write(bufferedImage, "png", fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            // 往压缩文件中添加文件
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOutputStream.putNextEntry(zipEntry);
            FileInputStream fileInputStream = new FileInputStream(fileUri);
            byte[] buffer = new byte[2048];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                zipOutputStream.write(buffer, 0, bytesRead);
            }
            fileInputStream.close();
            // 删除临时文件
            FileUtil.delete(new File(fileUri));
        }
        // 删除临时文件夹
        // FileUtil.delete(new File(filePath));
    }

}
